package com.baizhi.cmfz.service.impl;

import com.baizhi.cmfz.annotation.AddCacheAnnotation;
import com.baizhi.cmfz.annotation.DeleteCacheAnnotation;
import com.baizhi.cmfz.dao.UserDao;
import com.baizhi.cmfz.service.UserService;
import com.baizhi.cmfz.util.ThreadPollUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * This is a Class.
 *
 * @author zhanglh
 * @date 2019/09/11
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(readOnly = true)
    @AddCacheAnnotation
    public Map selectAllUser(int page, int limit, String userName) {
        page = (page - 1) * limit;
        Map<String, Object> map = new HashMap<>();
        map.put("data", userDao.selectAllByPage(page, limit, userName));
        map.put("count", userDao.countUser(userName));
        map.put("code", 0);
        return map;
    }

    @Override
    @DeleteCacheAnnotation
    public int updateStatus(int userId, int userStatus) {
        return userDao.updateUser(userId, userStatus);
    }

    @Override
    @Transactional(readOnly = true)
    @AddCacheAnnotation
    public Map showData() throws InterruptedException {
        Map<String, List<Map>> map = new HashMap<>();
        //创建线程池
        ThreadPoolExecutor executor = ThreadPollUtil.executor;
        //创建数量为3计数器
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //获得线程
        executor.submit(() -> {
            //查询性别数据
            map.put("sex", userDao.selectNumForSex());
            //计数器-1
            countDownLatch.countDown();
        });
        executor.submit(() -> {
            //查询用户注册时间数据
            map.put("date", userDao.selectNumForDate());
            //计数器-1
            countDownLatch.countDown();
        });
        executor.submit(() -> {
            //查询地区数据
            map.put("province", userDao.selectNumForProvince());
            //计数器-1
            countDownLatch.countDown();
        });
        countDownLatch.await();
        return map;
    }

    @Override
    public List<Map> showSexData() {
        return userDao.selectNumForSex();
    }

    //注册时间数据显示
    @Override
    public List<Map> showDateData() {
        return userDao.selectNumForDate();
    }

    @Override
    public List<Map> showProvinceData() {
        return userDao.selectNumForProvince();
    }
}
